package commConfig

import (
	"encoding/json"
	"fmt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEnv"
	"gitee.com/fierce_wolf/go-fox-edge-common/commLogger"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/FileName"
	"os"
)

var (
	config *InitialConfigService
	file   *InitialConfigFile
)

func init() {
	config = &InitialConfigService{}
	file = &InitialConfigFile{}
}

func InitializeByFilePath(configName string, fileName string) {
	err := initializeByFilePath(configName, fileName)
	if err != nil {
		commLogger.Error(fmt.Sprintf("初始化配置信息出错：\r\n配置名称=%v \r\n配置文件=%v \r\n出错信息=%v ", configName, fileName, configName))
	}
}

func initializeByFilePath(configName string, fileName string) error {
	filePath := FileName.GetOsFilePath(commEnv.Service.WorkDir + "/conf/" + commEnv.Service.ServiceType + "/" + commEnv.Service.ServiceName + "/" + fileName)

	jsn, err := os.ReadFile(filePath)
	if err != nil {
		return err
	}

	return config.Initialize(configName, string(jsn))
}

func TestFilePath(fileName string) error {
	filePath := FileName.GetOsFilePath(commEnv.Service.WorkDir + "/conf/" + commEnv.Service.ServiceType + "/" + commEnv.Service.ServiceName + "/" + fileName)

	jsn, err := os.ReadFile(filePath)
	if err != nil {
		return err
	}

	vo := make(map[string]interface{})
	return json.Unmarshal([]byte(jsn), &vo)
}

func Initialize(configName string, jsn string) error {
	return config.Initialize(configName, jsn)
}

func GetConfigParam(configName string) (map[string]interface{}, error) {
	return config.GetConfigParam(configName)
}
